package com.fjec.market.schedule.handler;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fjec.common.Const;
import com.fjec.market.entity.InfoBusiness;
import com.fjec.market.entity.InfoFarmer;
import com.fjec.market.entity.InfoPurchase;
import com.fjec.market.helper.MysqlShopNumHelper;
import com.fjec.market.service.IInfoBusinessService;
import com.fjec.market.service.IInfoPurchaseService;
import com.xxl.job.core.biz.model.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.elasticsearch.common.Strings;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class BusinessShopNumHandler {

    @Resource
    private IInfoBusinessService businessService;

    @Resource
    private MysqlShopNumHelper mysqlShopNumHelper;

    /**
     * 处理分拣、农资、包装的ShopNum
     *
     * @param limit
     * @param minutes
     * @return
     */
    public int handle(int limit, int minutes) {
        int num = 0;
        List<Map<String, Object>> mapList = businessService.getBusinessForShopNumGen(limit, minutes);
        for (Map<String, Object> map : mapList) {
            // 生成shopNum
            try {
                Long id = MapUtils.getLong(map, "Id");
                Integer busiType = MapUtils.getInteger(map, "BusiType");
                Integer markCode = MapUtils.getInteger(map, "MarkCode");
                if ((id != null && busiType != null && busiType != 4 && markCode != null)
                        || (id != null && busiType != null && busiType == 4 && markCode == null) ) {
                    if (busiType.intValue() == 4) {
                        markCode = Const.MARKET_CODE_MATERIAL;
//                        Long genNum = mysqlShopNumHelper.genShopNum(Const.MARKET_CODE_MATERIAL);
//                        strNum = String.format("%d%06d", Const.MARKET_CODE_MATERIAL, genNum);
                    }
                    Long genNum = mysqlShopNumHelper.genShopNum(markCode);
                    String strNum = String.format("%d%06d", markCode, genNum);
                    if (!Strings.isNullOrEmpty(strNum)) {
                        UpdateWrapper<InfoBusiness> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("Id", id);
                        InfoBusiness entity = new InfoBusiness();
                        entity.setShopNum(Long.valueOf(strNum));
                        businessService.update(entity, updateWrapper);
                        num++;
                    }
                }
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            }
        }
        return num;
    }


}
